/**
 * 
 */

package ar.com.ford.it.fullEconomics.view.action;

import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CurrencyFacade;
import ar.com.ford.it.fullEconomics.facade.EconomicIndexDefFacade;
import ar.com.ford.it.fullEconomics.facade.EconomicSourceFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese01Economic;
import ar.com.ford.it.fullEconomics.view.form.EconomicIndexDefForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

/**
 * @author vcanal
 * 
 */
public class EconomicIndexDefAction extends AbstractBaseAction {

    /**
     * Carga el formulario por defecto junto con las listas asociadas al mismo
     */
    public ActionForward initPage(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {

        EconomicIndexDefForm form = (EconomicIndexDefForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        form.resetForm();
        EconomicSourceFacade facadeSour = (EconomicSourceFacade) FacadeProvider
                .getFacade(request, EconomicSourceFacade.class);
        CurrencyFacade facadeCurr = (CurrencyFacade) FacadeProvider
                .getFacade(request, CurrencyFacade.class);
        try {
            request.getSession().setAttribute(
                    "economicSources",
                    facadeSour.findEconomicSources(null, null, user
                            .getTeesg01Plant()));
            request.getSession().setAttribute("economicMeasure",
                    facadeCurr.getAllCurrency());            
        } catch (FullEconomicsException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	form.setScreen("List");
        return mapping.findForward("success");
    }

    /**
     * Dirije la pantalla al browser de economicIndex
     */	
    public ActionForward browserPage(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {

        EconomicIndexDefForm form = (EconomicIndexDefForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        form.resetForm();
        EconomicSourceFacade facadeSour = (EconomicSourceFacade) FacadeProvider
                .getFacade(request, EconomicSourceFacade.class);
        CurrencyFacade facadeCurr = (CurrencyFacade) FacadeProvider
                .getFacade(request, CurrencyFacade.class);
        try {
            request.getSession().setAttribute(
                    "economicSources",
                    facadeSour.findEconomicSources(null, null, user
                            .getTeesg01Plant()));
            request.getSession().setAttribute("economicMeasure",
                    facadeCurr.getAllCurrency());            
        } catch (FullEconomicsException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }form.setScreen("detail");
	form.setCreate("new");
        return mapping.findForward("success");
    }
    /**
     * 
     * En caso de que la busqueda sea exacta muestra una pantalla que permita
     * modificar los datos en caso contrario muestra un listado de los economic
     * index buscados
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findEconomicIndexDef(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        ActionMessages am = new ActionMessages();
        EconomicIndexDefForm form = (EconomicIndexDefForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        Collection result = null;
        Teese01Economic resEco = null;
        EconomicIndexDefFacade facade = (EconomicIndexDefFacade) FacadeProvider
                .getFacade(request, EconomicIndexDefFacade.class);
        // Busqueda de Indice/s Economicos
        if (form.getState().equals("edit")) {
            if (StringUtils.isBlank(form.getCodeFind())) {
                if (form.getEconomicIndexDefSelected().getEese01EconNumberK() != null)
                    form.setCodeFind(form.getEconomicIndexDefSelected()
                            .getEese01EconNumberK().toString());
            }
        }
        
        try {
            if (StringUtils.isNotBlank(form.getCodeFind())
                    || StringUtils.isNotBlank(form.getDescFind())) {

                if (StringUtils.isNotEmpty(form.getCodeFind())) {

                    resEco = (facade.findEconomicIndexByCode(user
                            .getTeesg01Plant(), form.getCodeFind()));

                    form.setEconomicIndexDefSelected(resEco);
		    form.setScreen("detail");
                    if (form.getEconomicIndexDefSelected() == null) {
                        searchWithNoResults(request);
                        form.resetForm();
                    }
                } else {

                    result = facade.findEconomicIndexDef(null,
                            form.getDescFind(), form.getSourcFind(), user
                                    .getTeesg01Plant());
                    if (result.isEmpty()) {
                        searchWithNoResults(request);
                        form.resetForm();
                    } else {
                        if (result.size() > 1) {
                            form.setEconominIndex(result);
                            form.setScreen("List");
                        } else {
                            resEco = (Teese01Economic) result.iterator().next();
                            form.setEconomicIndexDefSelected(resEco);
			    form.setScreen("detail");
                        }
                    }
                }
            } else {
                // En el caso que la busqueda sea find all el metedo filtra por
                // source en caso de que sea necesario
                result = facade.findEconomicIndexDef(null, null, form
                        .getSourcFind(), user.getTeesg01Plant());
                form.setEconominIndex(result);
		form.setScreen("List");
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        if (resEco != null) {
            // Set de los atributos en el form
            form.setCurrency(resEco.getEese01CurrencyCodeC()
                    .getEesm01CurrencyCodeC());
            form
                    .setSourcSelec(String.valueOf(resEco
                            .getEese01EconsourceNumberR()
                            .getEese02EconsourceNumberK()));
            form.setEconominIndex(null);
        }
        return mapping.findForward("success");
    }

    public ActionForward createUpdateEconomicIndexDef(
            FordActionMapping mapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response,
            WebSession webSession, ActionMessages msgs, ActionMessages warns,
            ActionMessages errorMsgs) {
        ActionMessages am = new ActionMessages();
        EconomicIndexDefForm form = (EconomicIndexDefForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        EconomicIndexDefFacade facade = (EconomicIndexDefFacade) FacadeProvider
                .getFacade(request, EconomicIndexDefFacade.class);
        String desc = form.getEconomicIndexDefSelected().getEese01EconNameN();
        // Crear
        try {
            if (form.getCreate().equals("new") && form.getEconomicIndexDefSelected().getEese01EconNumberK()==null) {
                // Verifico que no la descripcion sea unica
                boolean isUnic = false;

                isUnic = facade.findUnicDescription(user.getTeesg01Plant(),
                        desc);

                if (isUnic) {

                    facade.createEconomicIndexDef(form
                            .getEconomicIndexDefSelected(), user, form
                            .getSourcSelec(), form.getCurrency());
                    form.setState("");
                    form.resetForm();

                } else
                    descriptionRepeat(request);
            } else {// Actualiza Economic Index

                facade.updateEconomicIndexDef(form
                        .getEconomicIndexDefSelected(), user, form
                        .getSourcSelec(), form.getCurrency());
             

            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    public ActionForward deleteEconomicIndexDef(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        ActionMessages am = new ActionMessages();
        EconomicIndexDefForm form = (EconomicIndexDefForm) actionForm;

        EconomicIndexDefFacade facade = (EconomicIndexDefFacade) FacadeProvider
                .getFacade(request, EconomicIndexDefFacade.class);
        // Valido que el Indice economico no tenga dependecias con otra tabla
        try {
            if (facade.deleteEconomicIndexDef(form
                    .getEconomicIndexDefSelected())) {
                form.resetForm();
            } else {
                this.messageError(request, "Indice Economico");
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        form.resetForm();
        return mapping.findForward("success");
    }

    public ActionForward newEconomicIndexDef(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {

        EconomicIndexDefForm form = (EconomicIndexDefForm) actionForm;
        errorMsgs = new ActionMessages();
        form.resetForm();
        form.setCreate("new");
	 form.setScreen("detail");
        return mapping.findForward("success");
    }

    private void messageError(HttpServletRequest request, String msg) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);
        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "error.delete.m", msg));
        saveMessages(request, am);
    }

    private void searchWithNoResults(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);
        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "message.noResults"));
        saveMessages(request, am);
    }
    private void descriptionRepeat(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);
        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "economicIndex.error.findEcounicDescription"));
        saveErrors(request, am);
    }


    public ActionForward proposeEconomicIndex(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        EconomicIndexDefForm form = (EconomicIndexDefForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        EconomicIndexDefFacade facade = (EconomicIndexDefFacade) FacadeProvider
                .getFacade(request, EconomicIndexDefFacade.class);

        if (facade.economicIndexCanBeProposed((form
                .getEconomicIndexDefSelected()))) {
            try {
                facade.proposeEconomicIndex(form.getEconomicIndexDefSelected(),
                        user);
            } catch (FullEconomicsException e) {
                ActionMessages am = new ActionMessages();
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
                saveErrors(request, am);
            }
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward approveEconomicIndex(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        EconomicIndexDefForm form = (EconomicIndexDefForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        EconomicIndexDefFacade facade = (EconomicIndexDefFacade) FacadeProvider
                .getFacade(request, EconomicIndexDefFacade.class);

        if (facade.economicIndexCanBeApproved((form
                .getEconomicIndexDefSelected()))) {
            try {
                facade.approveEconomicIndex(form.getEconomicIndexDefSelected(),
                        user);
            } catch (FullEconomicsException e) {
                ActionMessages am = new ActionMessages();
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
                saveErrors(request, am);
            }
        }
        return mapping.findForward("success");
    }

    public ActionForward screenList(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        EconomicIndexDefForm form = (EconomicIndexDefForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        EconomicIndexDefFacade facade = (EconomicIndexDefFacade) FacadeProvider
                .getFacade(request, EconomicIndexDefFacade.class);
        EconomicSourceFacade facadeSour = (EconomicSourceFacade) FacadeProvider
                .getFacade(request, EconomicSourceFacade.class);
        CurrencyFacade facadeCurr = (CurrencyFacade) FacadeProvider
                .getFacade(request, CurrencyFacade.class);
        form.resetForm();
        try {

            request.getSession().setAttribute(
                    "economicSources",
                    facadeSour.findEconomicSources(null, null, user
                            .getTeesg01Plant()));
            request.getSession().setAttribute("economicMeasure",
                    facadeCurr.getAllCurrency());
            form.setEconominIndex(facade.findAllEconomicIndex(user
                    .getTeesg01Plant()));
	    form.setEconominIndex(facade.findAllEconomicIndex(user
		    .getTeesg01Plant()));
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
	 form.setScreen("List");
        return mapping.findForward("success");
    }

    private void createOk(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);
        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "message.createOk"));
        saveMessages(request, am);
    }

}
